const fs = require('fs');
const path = require('path');

const type = process.argv[2];
const fileName = process.argv[3];

const fromPath = path.resolve(__dirname, '../pageData', type);
const toPath = path.resolve(__dirname, '../src', type, fileName);
const appJsonPath = path.resolve(__dirname, '../src/app.json');

// 目标文件夹不存在，创建
if (!fs.existsSync(toPath)) {
    fs.mkdirSync(toPath);
} else {
    throw Error('目标文件夹已存在,删除后重试');
}

const files = fs.readdirSync(fromPath, { withFileTypes: true });
console.log(files);

files.forEach((pathInfo) => {
    const fromFilePath = path.resolve(fromPath, pathInfo.name);
    const toFilePath = path.resolve(toPath, pathInfo.name);

    const readStream = fs.createReadStream(fromFilePath);
    const writeStream = fs.createWriteStream(toFilePath);

    readStream.pipe(writeStream);
});

if (type === 'pages') {
    const appJson = JSON.parse(fs.readFileSync(appJsonPath).toString());
    appJson.pages.push(`pages/${fileName}/index`);
    const jsonData = JSON.stringify(appJson);
    fs.writeFileSync(appJsonPath, jsonData);
}
